package com.qiaofang.globalexception;

import com.qiaofang.common.constant.CommonResponseCode;
import com.qiaofang.common.exception.BusinessException;
import com.qiaofang.common.exception.NotLoginException;
import com.qiaofang.common.exception.SystemException;
import com.qiaofang.common.response.CommonResponse;
import com.qiaofang.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice(basePackages = "com.qiaofang")
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        CommonResponse response = new CommonResponse();
        log.error("There is exception happening: {}", e);
        if (e instanceof NotLoginException) {
            response.setResponseCode(CommonResponseCode.RC_NOT_LOGIN_ERROR.getResponseCode());
            response.setResponseMessage(CommonResponseCode.RC_NOT_LOGIN_ERROR.getResponseMessage());
        } else if (e instanceof BusinessException) {
            response.setResponseCode(((BusinessException) e).getErrorCode());
            response.setResponseMessage(e.getMessage());
        } else if (e instanceof SystemException) {
            response.setResponseCode(((SystemException) e).getErrorCode());
            response.setResponseMessage(e.getMessage());
        } else if (e instanceof MethodArgumentNotValidException) {
            response.setResponseCode(CommonResponseCode.RC_PARAMETER_ERROR.getResponseCode());
            response.setResponseMessage(CommonResponseCode.RC_PARAMETER_ERROR.getResponseMessage());
        } else {
            response.setResponseCode(CommonResponseCode.RC_EXCEPTION_ERROR.getResponseCode());
            if (StringUtil.isNotBlank(e.getMessage())) {
                response.setResponseMessage(e.getMessage());
            } else {
                response.setResponseMessage(CommonResponseCode.RC_EXCEPTION_ERROR.getResponseMessage());
            }
        }
        return response;
    }

}
